
package com.kweative.lingua.server.protocol;

import com.kweative.lingua.server.structures.AppRequest;
import com.kweative.lingua.server.exceptions.NotFoundException;
import com.kweative.lingua.server.request.RequestHandler;
import com.kweative.lingua.server.response.ResponseHandler;
import com.kweative.network.HttpCookie;
import com.kweative.network.HttpResponse;
import com.kweative.network.Request;
import com.kweative.network.Response;
import com.kweative.type.Node;
import com.kweative.util.ArrayUtil;
import java.util.Date;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author henrik
 */

public class JsonSimpleProtocol extends Protocol {

    @Override
    public boolean canRead(RequestHandler request) {
        return (request.getFormat() instanceof com.kweative.format.JsonFormat);
    }

    @Override
    public AppRequest[] read(RequestHandler request) throws NotFoundException {
        throw new UnsupportedOperationException("Not supported yet.");
    }


    @Override
    public void write(ResponseHandler response, Node result) {
        try {
            if (response.getResponse() instanceof HttpResponse
                    && response.getSession() != null) {
                HttpCookie cookie = new HttpCookie(getSessionIdName(), response.getSession().getSID());
                Date d = new Date();
                cookie.setExpires(new Date(d.getTime() + getSessionExpire()));
                ((HttpResponse)response.getResponse()).addCookie(cookie);
            }
            com.kweative.format.JsonFormat format = new com.kweative.format.JsonFormat();
            String content = format.serialize(result);
            response.headers().put("Content-Type","application/json");
            response.setBody(content);
        } catch (Exception ex) {
            response.setStatus(Response.Status.E_INTERNAL);
            response.setBody("Could not properly format output");
            Logger.getLogger(JsonSimpleProtocol.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    @Override
    public void writeException(ResponseHandler response, Throwable ex) {
        try {
            Node error = new Node("error");
            error.makeChild("message", ex.getMessage());
            error.makeChild("stacktrace", ArrayUtil.join(ex.getStackTrace(), "\n"));
            write(response,error);
        } catch (Exception ex1) {
            Logger.getLogger(XmlSimpleProtocol.class.getName()).log(Level.SEVERE, null, ex1);
        }
    }
}
